package com.example.rouroudate.ui.home.ui

import android.annotation.SuppressLint
import android.content.Context
import android.util.AttributeSet
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.example.rouroudate.R
import com.example.rouroudate.util.DisplayUtils

@SuppressLint("UseCompatLoadingForDrawables")
class DateView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : ViewGroup(context, attrs, defStyleAttr) {

    private lateinit var backToday: TextView

    private lateinit var circleDateView: CircleDateView

    fun setDateView(startDate: CircleDate) {
        removeAllViews()
        circleDateView = CircleDateView(context).apply {
            setStartDate(startDate)
        }
        backToday = TextView(context).apply {
            text = context.getString(R.string.back_today)
            background = context.getDrawable(R.drawable.circle_rectangle)
            gravity = Gravity.CENTER
            visibility = if (startDate.isCurrentDate()) View.GONE else View.VISIBLE
        }
        val layoutParams = LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)
        val lp = LayoutParams(DisplayUtils.dp2px(100f), DisplayUtils.dp2px(40f))
        addView(circleDateView, layoutParams)
        addView(backToday, lp)
    }

    fun setBackToday(listener: OnClickListener) {
        backToday.setOnClickListener(listener)
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        for (i in 0 until childCount) {
            val child = getChildAt(i)
            measureChild(child, widthMeasureSpec, heightMeasureSpec)
        }
    }

    override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
        for (i in 0 until childCount) {
            when(val child = getChildAt(i)) {
                is CircleDateView -> {
                    child.layout(0, 0, child.measuredWidth, child.measuredHeight)
                }
                else -> {
                    val w = child.measuredWidth
                    val h = child.measuredHeight
                    val displayWidth = DisplayUtils.getScreenWidth()
                    val l = (displayWidth - w) / 2
                    val t = displayWidth / 3.6f + DisplayUtils.dp2px(20f)
                    child.layout(l, t.toInt(), l + w, t.toInt() + h)
                }
            }
        }
    }

}